/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.com.neolokura.travian.helper.batch;

import ar.com.neolokura.travian.helper.troop.entity.TroopDetail;
import ar.com.neolokura.travian.helper.batch.logic.TravianHelperBatchLogic;
import ar.com.neolokura.travian.helper.bo.object.LoginObject;
import ar.com.neolokura.travian.helper.facade.ServiceFacade;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import org.apache.http.NoHttpResponseException;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 *
 * @author gustavo
 */
public class TravianHelperBatch {

    private static Logger logger = Logger.getLogger(TravianHelperBatch.class.getSimpleName());

    public TravianHelperBatch() {
    }

    // Remember to use quartz for every job is done!
    public void runTravianHelperBatch() throws Exception {

        String userName = "molotov";
        String password = "rul1n22";

        // Batch started Up Time! Not so useful, but pretty! =D
        DateTime startUp = DateTime.now();
        DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss - dd/MM");

        ServiceFacade facade = ServiceFacade.getInstance();
        TravianHelperBatchLogic logic = new TravianHelperBatchLogic();

        HashMap<String, TroopDetail> troopList = new HashMap<String, TroopDetail>();

        do {
            try {


                // Checks if it's logged! If not, logs in!
                if (!facade.isLogged()) {

                    logger.info("User " + userName + "is not logged! Loggin' in...");
                    facade.login(userName, password);
                }



                // START PROWSER WORKING

                //Gets all villages Ids!
                ArrayList<Integer> villageIds = new ArrayList<Integer>();
                villageIds.add(23175);
                villageIds.add(95585);
                villageIds.add(109414);
                // Check all incoming troops!
                HashMap<String, TroopDetail> troopsIncoming = facade.getIncomingTroops(villageIds);

                String report = "";

                for (Entry<String, TroopDetail> entry : troopsIncoming.entrySet()) {

                    TroopDetail detail = entry.getValue();

                    Boolean existsDetail = false;
                    for (Entry<String, TroopDetail> actualEntry : troopList.entrySet()) {

                        TroopDetail actualTroop = actualEntry.getValue();
                        if (detail.equals(actualTroop)) {
                            existsDetail = true;
                        }

                    }

                    if (existsDetail) {
                        break;
                    }

                    String detailType = detail.getDetailType();
                    DateTime arrivalDate = detail.getArrivalDate();
                    Duration arrivalDuration = detail.getArrivalDuration();



                    if (detailType != null) {

                        report += "\nVillage " + detail.getVillageId() + ":";
                        Boolean existsAttack = detailType.contains("inAttack");
                        Boolean existsRaid = detailType.contains("inRaid");
                        Boolean existsSupply = detailType.contains("inSupply");
                        Boolean existsReturn = detailType.contains("inReturn");
                        Boolean existsTroopsIncoming = existsAttack || existsRaid || existsSupply || existsReturn;



                        if (existsAttack || existsRaid) {
                            //TODO: under Attack! Check if it's a fake or not!
                            //TODO: add sending messages and/or mails!
                            report += "\n has an attack incoming!";
                        }

                        if (existsSupply) {
                            //TODO: Supplies Incoming!
                            report += "\n has supplies incoming!";

                        }

                        if (existsReturn) {
                            //TODO: Troops returning!
                            report += "\n has troops returning!";

                        }

                        // If existsTroopsIncoming add duration and time arrival to the report
                        report += existsTroopsIncoming ? " in " + logic.getDuration(arrivalDuration) + " @ " + arrivalDate.toString(format) : "";

                    }
                    troopList.put(detail.getId(), detail);
                }
                if (!report.isEmpty()) {
                    System.out.println(report);
                }

                //Cleans old troop!
                logic.backupTroopList(troopList);
                logic.cleanOldTroopList(troopList);


                // END PROWSER WORKING





                // Time Manager

                logic.waitSeconds(15, 17);
            } catch (NoHttpResponseException nhre) {
                logger.error("Not connected! reconecting...");
            }
        } while (true);


    }

    public static void main(String[] args) {

        TravianHelperBatch batch = new TravianHelperBatch();


        try {
            batch.runTravianHelperBatch();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }

        System.exit(0);
    }
}
